import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/model/bank_card.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:leader_doctor_flutter/ui/wallet/event/reflect_event.dart';
import 'package:leader_doctor_flutter/ui/wallet/model/withdraw_info_model.dart';

/// @Author lixiaobin
/// @Date 2024/1/30
/// @Description 钱包提现
class WalletReflectPage extends StatefulWidget {
  const WalletReflectPage({super.key});

  @override
  State<WalletReflectPage> createState() => _WalletReflectPageState();
}

class _WalletReflectPageState extends State<WalletReflectPage> {
  final _textEditingController = TextEditingController();
  final _emailEditingController = TextEditingController();
  var _getMoney = "0.00";
  WithdrawInfoModel? _withdrawInfoModel;
  BankCardModel? _userBankAccount;
  var _btnSelect = false;

  @override
  void initState() {
    super.initState();

    _editListener();
    _withdrawInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: CommWidget.getCommAppbar(context),
        body: Container(
            color: ColorRes.colorf7f7f7,
            height: double.infinity,
            child: Column(children: [
              GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    context.push(PageUrl.bankCardManage).then((value) => _withdrawInfo());
                  },
                  child: Container(
                      padding: EdgeInsets.only(left: 23.w, right: 16.w),
                      height: 120.w,
                      width: double.infinity,
                      child: Row(children: [
                        Expanded(
                            child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(_userBankAccount?.openingBank ?? '',
                                style: TextStyle(
                                    color: ColorRes.color333333, fontSize: 16.sp, fontWeight: FontWeight.bold)),
                            SizedBox(height: 13.w),
                            Text(_getBankAccount(_userBankAccount),
                                style: TextStyle(color: ColorRes.color808080, fontSize: 14.sp)),
                          ],
                        )),
                        ImageLoader.loadAsset('icon_white_arrow.webp', 0,
                            size: Size(10.w, 12.w), color: ColorRes.color333333)
                      ]))),
              Container(
                  color: ColorRes.white,
                  padding: EdgeInsets.only(left: 23.w, top: 28.w, bottom: 28.w, right: 16.w),
                  child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                    Text('提现金额', style: TextStyle(color: ColorRes.color333333, fontSize: 14.sp)),
                    Row(children: [
                      Text('￥',
                          style: TextStyle(color: ColorRes.color333333, fontSize: 30.sp, fontWeight: FontWeight.bold)),
                      Expanded(
                          child: TextField(
                              controller: _textEditingController,
                              style:
                                  TextStyle(color: ColorRes.color333333, fontSize: 30.sp, fontWeight: FontWeight.bold),
                              inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'[0-9.]'))],
                              decoration: const InputDecoration(hintText: '0.00', border: InputBorder.none))),
                    ]),
                    SizedBox(height: 20.w),
                    Container(color: ColorRes.colorF0F0F0, height: 1.w),
                    SizedBox(height: 14.w),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('可提现金额${StringUtils.formatNumber(_withdrawInfoModel?.noWithdrawFee)}元',
                            style: TextStyle(color: ColorRes.colorB3B3B3, fontSize: 12.sp)),
                        GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {
                              _textEditingController.text = StringUtils.formatNumber(_withdrawInfoModel?.noWithdrawFee);
                              setState(() {});
                            },
                            child: Text('全部提现', style: TextStyle(color: ColorRes.colorMain, fontSize: 12.sp)))
                      ],
                    ),
                  ])),
              SizedBox(height: 6.w),
              Container(
                  color: ColorRes.white,
                  padding: EdgeInsets.fromLTRB(23.w, 35.w, 16.w, 35.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text('到账金额:', style: TextStyle(color: ColorRes.colorMain, fontSize: 18.sp)),
                          Row(children: [
                            Text('￥',
                                style: TextStyle(
                                    color: ColorRes.color666666, fontSize: 30.sp, fontWeight: FontWeight.bold)),
                            Text(_getMoney,
                                style: TextStyle(
                                    color: ColorRes.color666666, fontSize: 30.sp, fontWeight: FontWeight.bold))
                          ]),
                        ],
                      ),
                      SizedBox(height: 30.w),
                      Container(color: ColorRes.colorf0f0f0, height: 1.w),
                      SizedBox(height: 13.w),
                      Text('到账金额 = 提现金额',
                          style: TextStyle(color: ColorRes.colorb2b2b2, fontSize: 12.sp, fontWeight: FontWeight.bold))
                    ],
                  )),
              SizedBox(height: 52.w),
              Container(
                  padding: EdgeInsets.only(right: 12.w, left: 12.w),
                  child: CommWidget.buildRightBtn('确认提现', () {
                    if (_btnSelect) _submit();
                  }, isSelect: _btnSelect)),
            ])));
  }

  /// 输入框监听
  _editListener() {
    _textEditingController.addListener(() {
      var text = _textEditingController.text;

      // 输入'' 修正为0.00
      if (text == '') {
        text = '0.00';
      }

      // 输入.开头修正为0.
      if (text.startsWith('.')) {
        text = '0.';
        _textEditingController.text = '0.';
      }

      //01修证为0.1
      if (text.length == 2 && text.startsWith('0') && !text.endsWith('.')) {
        var str = '0.${text[1]}';
        text = str;
        _textEditingController.text = str;
      }

      //保留小数点后两位 0.01
      var indexOf = text.indexOf('.');
      if (indexOf > -1 && text.length - 1 - indexOf > 2) {
        var str = text.substring(0, text.length - 1);
        text = str;
        _textEditingController.text = str;
      }

      //输入的金额小于可提现金额
      if (_withdrawInfoModel != null) {
        var noWithdrawFee = _withdrawInfoModel?.noWithdrawFee ?? 0;
        var inputNum = (double.parse(text) * 100).toInt();
        var num = noWithdrawFee - inputNum;
        if (num < 0) {
          text = StringUtils.formatNumber(noWithdrawFee);
          _textEditingController.text = StringUtils.formatNumber(noWithdrawFee);
          Fluttertoast.showToast(msg: '输入的金额必须小于可提现金额');
        }

        _btnSelect = inputNum > 0;
      }
      _getMoney = text;
      setState(() {});
    });
  }

  /// 账户余额
  _withdrawInfo() async {
    var user = App.instance.userInfo;
    var response = await HttpClient.post(HttpRequest(Api.withdrawInfo, urlParams: {'doctorId': user?.id}));
    var serviceResult = ServiceResult<WithdrawInfoModel>(response, (map) => WithdrawInfoModel.fromJson(map));
    if (serviceResult.success) {
      _withdrawInfoModel = serviceResult.responseBody;
      _userBankAccount = _withdrawInfoModel?.userBankAccount;
      setState(() {});
    } else {
      Fluttertoast.showToast(msg: serviceResult.responseMsg ?? '');
    }
  }

  /// 修改医生邮箱
  _updateUserEmail(String email) async {
    var user = App.instance.userInfo;
    var response =
        await HttpClient.postJson(HttpRequest(Api.updateUserEmail, body: {'userId': user?.id, 'email': email}));
    var serviceResult = ServiceResult<dynamic>.simple(response);
    String msg = "邮箱设置成功";
    if (serviceResult.success) {
      NativeInterface().setEmail(email);
    } else {
      msg = serviceResult.responseMsg ?? '';
    }
    Fluttertoast.showToast(msg: msg);
  }

  String _getBankAccount(BankCardModel? model) {
    var bankAccount = model?.bankAccount;
    var substring = bankAccount?.substring(bankAccount.length - 4) ?? '';
    return '尾号$substring${model?.accountType ?? ''}';
  }

  /// 提交数据
  _submit() async {
    if (_withdrawInfoModel == null) {
      return;
    }
    var user = await NativeInterface().getUserInfo();
    var money = _textEditingController.text.toString().trim();
    var parse = (double.parse(money) * 100).toInt();
    if (StringUtils.isEmpty(money)) {
      Fluttertoast.showToast(msg: '请输入提现金额');
      return;
    }

    //邮箱判断
    if (StringUtils.isEmpty(user.email)) {
      _showEmailDialog();
      return;
    }

    //最小提现金额大于100
    if (!App.isDebug) {
      if (parse < 10000) {
        Fluttertoast.showToast(msg: '最小提现金额大于100元');
        return;
      }
    }

    var response = await HttpClient.postJson(HttpRequest(Api.orderRealtime, body: {
      'real_name': _userBankAccount?.name,
      'card_no': _userBankAccount?.bankAccount,
      'phone_no': user?.phone,
      'id_card': _userBankAccount?.idNumber,
      'pay': money,
      'userId': user?.id,
      'userType': '2',
      'totalFee': money,
      'serviceFee': '0.00',
      'taxFee': '0.00',
      'bankName': _userBankAccount?.openingBank,
    }));
    var serviceResult = ServiceResult<dynamic>.simple(response);
    if (serviceResult.success) {
      Fluttertoast.showToast(msg: '提现成功');
      if (!mounted) return;
      context.pop();
    } else {
      Fluttertoast.showToast(msg: serviceResult.responseMsg ?? '');
    }
  }

  /// 补充身份证照片
  _showEmailDialog() {
    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              child: Container(
                  height: 250.w,
                  width: double.infinity,
                  decoration: BoxDecoration(color: ColorRes.white, borderRadius: BorderRadius.circular(5.w)),
                  child: Column(
                    children: [
                      SizedBox(height: 22.w),
                      Text('温馨提示',
                          style: TextStyle(color: ColorRes.color333333, fontSize: 17.sp, fontWeight: FontWeight.bold)),
                      SizedBox(height: 22.w),
                      Container(
                          margin: EdgeInsets.only(right: 15.w, left: 15.w),
                          height: 50.w,
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                              color: ColorRes.white,
                              borderRadius: BorderRadius.circular(5.w),
                              border: Border.all(color: ColorRes.colordddddd, width: 1.w)),
                          child: TextField(
                              controller: _emailEditingController,
                              scrollPadding: EdgeInsets.zero,
                              style: TextStyle(color: ColorRes.color333333, fontSize: 14.sp),
                              decoration: const InputDecoration(
                                  contentPadding: EdgeInsets.zero,
                                  hintText: '请输入您的电子邮箱......',
                                  border: InputBorder.none))),
                      SizedBox(height: 15.w),
                      Container(
                          padding: EdgeInsets.only(left: 28.w, right: 28.w),
                          child: Text('电子邮箱用于向您发送在平台收入的完税证明，请填写准确！',
                              style: TextStyle(color: ColorRes.color666666, fontSize: 16.sp))),
                      Expanded(child: Container()),
                      Container(color: ColorRes.colorEEF2F5, height: 1),
                      SizedBox(
                        height: 50.w,
                        width: double.infinity,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Expanded(
                              child: GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    context.pop(0);
                                  },
                                  child: Text('取消',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(color: ColorRes.color666666, fontSize: 17.sp))),
                            ),
                            Container(
                              width: 1,
                              color: ColorRes.colorEEF2F5,
                            ),
                            Expanded(
                              child: GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    var text = _emailEditingController.text.toString().trim();
                                    if (StringUtils.isEmpty(text)) {
                                      Fluttertoast.showToast(msg: '您还未输入电子邮箱');
                                      return;
                                    }
                                    if (!text.contains('@')) {
                                      Fluttertoast.showToast(msg: '邮箱格式不正确');
                                      return;
                                    }
                                    context.pop(text);
                                  },
                                  child: Text('确定',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(color: ColorRes.color518DF6, fontSize: 17.sp))),
                            )
                          ],
                        ),
                      )
                    ],
                  )));
        }).then((value) {
      if (value != 0) {
        _updateUserEmail(value);
      }
    });
  }
}
